package com.rm.zeyou.util.date;/**
 *
 */

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Description:
 *
 * @author : YanYang
 */
public class DateUtils {

    public static final String DATETIMEFORMAT = "yyyyMMddHHmmss";

    public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String DATE_TIME_Today = "yyyy-MM-dd";

    public static final long TIME_OF_MINUTE = 60000L;

    public static final long TIME_OF_HOUR = 3600000L;

    public static final long TIME_OF_DAY = 86400000L;

    /**
     * 将[日期]按照给定的[日期格式]转成[字符串]
     *
     * @param date   日期
     * @param format 日期格式
     * @return
     */
    public static String parseDateToString(Date date, String format) {
        if (date == null) {
            return null;
        }
        if (StringUtils.isEmpty(format)) {
            format = DATE_TIME_FORMAT;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    public static String getDateForNumber(Date date, String format) {
        if (date == null) {
            return null;
        }
        if (StringUtils.isEmpty(format)) {
            format = DATETIMEFORMAT;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 将[时间]按照指定的[日期格式]转成[字符串]
     *
     * @param time   时间
     * @param format 日期格式
     * @return
     */
    public static String parseLongToString(long time, String format) {
        SimpleDateFormat mydate = new SimpleDateFormat(format);
        return mydate.format(new Date(time));
    }

    /**
     * 将[字符串]按照指定的[日期格式]转成[时间]
     *
     * @param time   字符串
     * @param format 日期格式
     * @return
     */
    public static long parseStringToLong(String time, String format) {
        SimpleDateFormat mydate = new SimpleDateFormat(format);
        try {
            Date date = mydate.parse(time);
            if (date != null) {
                return date.getTime();
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 将[字符串]按照指定的[日期格式]转成[日期]
     *
     * @param time   字符串
     * @param format 日期格式
     * @return
     */
    public static Date parseStringToDate(String time, String format) {
        SimpleDateFormat mydate = new SimpleDateFormat(format);
        try {
            Date date = mydate.parse(time);
            if (date != null) {
                return date;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 添加天数
     *
     * @param date   日期
     * @param amount 增加天数
     * @return
     */
    public static Date addDay(Date date, int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.add(Calendar.DAY_OF_MONTH, amount);

        return calendar.getTime();
    }


    /**
     * 添加月数
     *
     * @param date   日期
     * @param amount 增加月数
     * @return
     */
    public static Date addMonth(Date date, int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.add(Calendar.MONTH, amount);

        return calendar.getTime();
    }

    /**
     * 获取某天的开始时间
     *
     * @param date 日期
     */
    public static Date getStartTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取某天的结束时间
     *
     * @param date 日期
     */
    public static Date getEndTime(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }


    /**
     * 前七天的全部日期(年月日)
     *
     * @return
     */
    public static List<String> getBeforeSevenDay(String date) {

        String[] arr = new String[7];

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar c = null;

        for (int i = 0; i < 7; i++) {

            c = Calendar.getInstance();
            c.setTime(parseStringToDate(date, DATE_TIME_Today));
            c.add(Calendar.DAY_OF_MONTH, -i - 1);

            arr[6 - i] = sdf.format(c.getTime());

        }

        List<String> beforeSevenDayList = new ArrayList<>();
        for (int i = 6; i < arr.length; i--) {
            beforeSevenDayList.add(arr[i]);
            if (i == 0) {
                break;
            }
        }
        return beforeSevenDayList;

    }

    /**
     * @param inputJudgeDate 要判断是否在当天24h内的时间
     * @return boolean
     */
    public static boolean isToday(Date inputJudgeDate) throws ParseException {
        boolean flag = false;
        // 获取当前系统时间
        long longDate = System.currentTimeMillis();
        Date nowDate = new Date(longDate);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(nowDate);
        String subDate = format.substring(0, 10);
        // 定义每天的24h时间范围
        String beginTime = subDate + " 00:00:00";
        String endTime = subDate + " 23:59:59";
        Date paseBeginTime;
        Date paseEndTime;

        paseBeginTime = dateFormat.parse(beginTime);
        paseEndTime = dateFormat.parse(endTime);


        if (inputJudgeDate.after(paseBeginTime) && inputJudgeDate.before(paseEndTime)) {
            flag = true;
        }
        return flag;
    }

    /**
     * @param paramDate 要判断是否在昨天24h内的时间
     * @return boolean
     */
    public static boolean judgeYesterday(Date paramDate) throws ParseException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String todayStr = format.format(date);
        // 得到今天零时零分零秒这一时刻
        Date today = format.parse(todayStr);
        // 与今日零时零分零秒比较
        if ((today.getTime() - paramDate.getTime()) > 0 && (today.getTime() - paramDate.getTime()) < 86400000) {
            return true;
        }
        return false;
    }


    /**
     * 获取当前时间前一小时的时间
     *
     * @param date
     * @return java.util.Date
     */
    public static Date beforeOneHourToNowDate(Date date, int dayHours) {
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, -dayHours);
        return calendar.getTime();
    }

    /**
     * 获取当前时间后一小时的时间
     *
     * @param date
     * @return java.util.Date
     */
    public static Date afterOneHourToNowDate(Date date, int dayHours) {
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.setTime(date);
        calendar.add(Calendar.HOUR_OF_DAY, dayHours);
        return calendar.getTime();
    }


    /**
     * 分割时间段
     *
     * @param dateType 类型 M/D/H/N -->每月/每天/每小时/每分钟
     * @param dBegin   开始时间
     * @param dEnd     结束时间
     * @param time     指定小时(如：1、2、3、4)
     * @return
     */
    public static List<String> findDates(String dateType, Date dBegin, Date dEnd, int time) throws Exception {
        List<String> listDate = new ArrayList<>();
        listDate.add(new SimpleDateFormat("MM-dd HH:mm").format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        calEnd.setTime(dEnd);

        while (calEnd.after(calBegin)) {
            if ("H".equals(dateType)) {
                calBegin.add(Calendar.HOUR, time);
            }
            if ("M".equals(dateType)) {
                calBegin.add(Calendar.MONTH, time);
            }
            if ("D".equals(dateType)) {
                calBegin.add(Calendar.DATE, time);
            }
            if ("N".equals(dateType)) {
                calBegin.add(Calendar.MINUTE, time);
            }
            // 判断当前时间是否在9:00-23:00之间，如果不在则跳过
            //if (calBegin.get(Calendar.HOUR_OF_DAY) < 9) {
            //    continue;
            //} else {
                calBegin.get(Calendar.HOUR_OF_DAY);
            //}
            if (calEnd.after(calBegin)) {
                listDate.add(new SimpleDateFormat("MM-dd HH:mm").format(calBegin.getTime()));
            } else {
                // listDate.add(new SimpleDateFormat("MM-dd HH:mm").format(calEnd.getTime()));
            }

        }
        return listDate;
    }



    /**
     * 添加分钟数
     *
     * @param date   日期
     * @param amount 增加分钟数
     * @return
     */
    public static Date addMinute(Date date, int amount) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        calendar.add(Calendar.MINUTE, amount);

        return calendar.getTime();
    }

    // 24 * (differ / dayM) 这里拿到被舍弃的整数，整数是几，就代表相隔几天，一天24小时，那就整数乘以24即可。
    public static String getDifferHour(Date startDate, Date endDate) {
        long startDateTime = startDate.getTime();
        long endDateTime = endDate.getTime();
        long diff = (endDateTime - startDateTime) / 1000 / 60;
        long hours = diff / 60; // 将分钟转换为小时
        long remainingMinutes = diff % 60; // 获取不足一小时的分钟部分
        double decimal = Double.parseDouble(String.valueOf(hours).concat(".").concat(String.valueOf(remainingMinutes)));
        // return decimal + "h";
        return decimal + "";
    }

    public static String getDifferyear(Date startDate, Date endDate) {
        // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // String str1 = "2012-02-05";
        // String str2 = "2014-02-06";
        // Calendar bef = Calendar.getInstance();
        // Calendar aft = Calendar.getInstance();
        // bef.setTime(startDate);
        // aft.setTime(endDate);
        // int surplus = aft.get(Calendar.DATE) - bef.get(Calendar.DATE);
        // int result = aft.get(Calendar.MONTH) - bef.get(Calendar.MONTH);
        // int year = aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR);
        // System.out.println(result);
        // if (result > 0) {
        //     result = 1;
        // } else if (result == 0) {
        //     result = surplus <= 0 ? 0 : 1;
        // } else {
        //     result = 0;
        // }
        // System.out.println(result);
        // System.out.println("相差年份：" + (year + result));
        // return "相差年份：" + (year + result);

        // 假设有两个日期对象 date1 和 date2
        Date date1 = startDate; // 第一个日期
        Date date2 = endDate; // 第二个日期

        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        int year1 = cal1.get(Calendar.YEAR);
        int month1 = cal1.get(Calendar.MONTH);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int year2 = cal2.get(Calendar.YEAR);
        int month2 = cal2.get(Calendar.MONTH);

        int yearDifference = year2 - year1;
        int monthDifference = month2 - month1;

        if (monthDifference < 0) {
            yearDifference--;
            monthDifference += 12;
        }

        // System.out.println("Year difference: " + yearDifference);
        // System.out.println("Month difference: " + monthDifference);
        return yearDifference + "," + monthDifference;
    }


    public static String getDifferDay(Date startDate, Date endDate) {
        DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        // Date star = dft.parse("2020-02-03");// 开始时间
        // Date endDay = dft.parse("2025-03-02");// 结束时间
        Long starTime = startDate.getTime();
        Long endTime = endDate.getTime();
        Long num = endTime - starTime;// 时间戳相差的毫秒数
        System.out.println("相差天数为：" + num / 24 / 60 / 60 / 1000);// 除以一天的毫秒数
        return num / 24 / 60 / 60 / 1000 + "";
    }

    /**
     * 计算两个日期相差的秒数
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static long calLastedTime(Date startDate, Date endDate) {
        long a = endDate.getTime();
        long b = startDate.getTime();

        return ((a - b) / 1000);
    }


    /**
     * 日期转星期
     *
     * @param datetime "2017-01-01"
     * @return
     */
    public static String dateToWeek(String datetime) {

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) ; // 指示一个星期中的某天。
        if (w < 0) {
            w = 0;
        }
        return weekDays[w-1];

    }

    /**
     * 将日期转为周几 如果时间为下周 显示 下周几 以此类推
     * @Date 2025 3月 06 15:50
     * @param targetDate
     * @return
     */
    public static String getWeek(Date targetDate) {
        int targetWeek = DateUtil.dayOfWeek(targetDate);
        //目标时间与本周最后一天时间比较
        long between = DateUtil.between(DateUtil.endOfWeek(new Date()), targetDate, DateUnit.HOUR, false);
        System.out.println("between = " + between);
        // 判断并生成描述
        String description;
    try {
        if (isToday(targetDate)) {
            description = "今天";
        }else if (between >= -168 && between < 0) { // -168小时即-7天
            description = "周" + getChineseWeekDay(targetWeek);
        } else if (between >= -336 && between < -168) { // -336小时即-14天
            description = "上周" + getChineseWeekDay(targetWeek);
        }else if (between > 0 && between <= 168) { // 168小时即7天
            description = "下周" + getChineseWeekDay(targetWeek);
        } else if (between > 168 && between <= 336) { // 336小时即14天
            description = "下下周" + getChineseWeekDay(targetWeek);
        }else {
            // 更远的时间范围，可以根据需求进一步细化描述
            description = "未来周" + getChineseWeekDay(targetWeek);
        }
    } catch (ParseException e) {
        throw new RuntimeException(e);
    }


        //if (between >= -168 && between < 0) { // -168小时即-7天
        //    description = "周" + getChineseWeekDay(targetWeek);
        //} else if (between >= -336 && between < -168) { // -336小时即-14天
        //    description = "上周" + getChineseWeekDay(targetWeek);
        //} else {
        //    try {
        //        if (isToday(targetDate)) {
        //            description = "今天";
        //        } else if (between > 0 && between <= 168) { // 168小时即7天
        //            description = "下周" + getChineseWeekDay(targetWeek);
        //        } else if (between > 168 && between <= 336) { // 336小时即14天
        //            description = "下下周" + getChineseWeekDay(targetWeek);
        //        } else {
        //            // 更远的时间范围，可以根据需求进一步细化描述
        //            description = "未来周" + getChineseWeekDay(targetWeek);
        //        }
        //    } catch (ParseException e) {
        //        throw new RuntimeException(e);
        //    }
        //}
        return description;
    }



    public static void main(String[] args) throws ParseException {
        System.out.println(getWeek(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2025-05-01 09:00:00")));
    }

    private static String getChineseWeekDay(int weekDay) {
        String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};
        return weekDays[weekDay - 1];
    }

}
